from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import sessionmaker

from commons.entity.po.travel_approval import TravelApproval
from commons.mappers.base_mapper import BaseMapper

# 创建数据库引擎
db_url = "mysql+pymysql://root:123456@localhost/ctdb"
engine = create_engine(db_url, echo=True)

# 创建会话类
Session = sessionmaker(bind=engine)


class TravelApprovalMapper(BaseMapper):
    def __init__(self):
        super().__init__(Session)

    def select_by_travel_approval_id(self, travel_approval_id):
        """
        根据 travel_approval_id 从数据库获取 TravelApproval 对象
        :param travel_approval_id: str
        :return: TravelApproval 对象或 None
        """
        try:
            with self.session_factory() as session:
                travel_approval = session.query(TravelApproval).filter_by(
                    travel_approval_id=travel_approval_id).first()
                if travel_approval:
                    return travel_approval
                return None
        except SQLAlchemyError as e:
            print(f"Database error: {str(e)}")
            return None

    def delete_by_travel_approval_id(self, travel_approval_id):
        """
        根据 travel_approval_id 删除审批出差申请记录
        :param travel_approval_id: str
        :return: True（删除成功）或 False（失败）
        """
        try:
            with self.session_factory() as session:
                travel_approval = session.query(TravelApproval).filter_by(
                    travel_approval_id=travel_approval_id).first()
                if travel_approval:
                    session.delete(travel_approval)
                    session.commit()  # 提交事务
                    return True
                return False  # 记录不存在
        except SQLAlchemyError as e:
            print(f"Database error during delete operation: {str(e)}")
            return False

    def update_by_travel_approval_id(self, travel_approval_update, travel_approval_id):
        """
        根据 travel_approval_id 更新审批出差申请记录
        :param travel_approval_id: str
        :param travel_approval_update: TravelApproval 类实例或字典，包含需要更新的字段
        :return: True（更新成功）或 False（失败）
        """
        try:
            with self.session_factory() as session:
                travel_approval = session.query(TravelApproval).filter_by(
                    travel_approval_id=travel_approval_id).first()
                if travel_approval:
                    # 如果 travel_approval_update 是类实例，转换为字典
                    if travel_approval_update and hasattr(travel_approval_update, 'to_dict'):
                        travel_approval_update = travel_approval_update.to_dict()

                    # 使用新数据更新记录属性
                    for key, value in travel_approval_update.items():
                        if value is not None and hasattr(travel_approval, key):
                            setattr(travel_approval, key, value)

                    session.commit()  # 提交事务
                    return True
                return False  # 记录不存在
        except SQLAlchemyError as e:
            print(f"Database error during update operation: {str(e)}")
            return False

    def select_by_travel_id(self, travel_id):
        """
        根据 travel_id 从数据库获取 TravelApproval 对象
        :param travel_id:
        :return: TravelApproval 对象或 None
        """
        try:
            with self.session_factory() as session:
                travel_approval = session.query(TravelApproval).filter_by(travel_id=travel_id).first()
                if travel_approval:
                    return travel_approval
                return None
        except SQLAlchemyError as e:
            print(f"Database error: {str(e)}")
            return None